package com.hsmpay.common.util.jiami;

import com.hsmpay.utils.system.PbkConfig;
import it.sauronsoftware.base64.Base64;
import org.apache.log4j.Logger;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.Security;
import java.util.LinkedHashMap;
import java.util.Map;

public class HttpClientUtils {
    public static String marhuiPublicKey = PbkConfig.getAttribute("MARHUI_PUB_KEY").trim();
//            "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCzCEGUT6yzqI33ZZReJCm3KvLG" + "\r" +
//            "DxKM77mEDx0czJr93HCA+KkFcd20mPoAwYCAHMgzvWm6BK7sf+BwS9qcIjEuxinD" + "\r" +
//            "LBZBuE/+uyPmJgTfFME8WEXBhcO1fPvNa9+Mr6aEwM8l1UD3IQAfGRkbr7RthOmB" + "\r" +
//            "1GgTvrhXynHrehtcAwIDAQAB" + "\r";

    private static final String DEFAULT_PRIVATE_KEY =
            "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAKyRht3mRFhkBNFC" + "\r" +
                    "AS5x3VVVmHoZbJP73l/K40bmRmbgDIu8lp5R3aPbahYfVoo+PUpWUKxmPD7SzDnh" + "\r" +
                    "8g3xlYS4hufWh5IpnNhHxoIqoJWIZuf0U6k7ao99mbZPZSdXmjpmrnjvWXYu42LA" + "\r" +
                    "0tMOpu7DxSaeOPrqj9JgQ5a5cFZrAgMBAAECgYEApvJa0U21jPWmG3OJhQ8vGyEl" + "\r" +
                    "0+nIuxmNtoqnea3JKjlSqdUWua9lhuH8Lc6/gBpaXRJIFaEKY5S3cr/91jODez3q" + "\r" +
                    "Grngl/D/AMsx/NAaj30XzUAf3OObKWVTZdNERUUuxafeLM8xNbhUhS0F8AMdc8z3" + "\r" +
                    "O/u+w3HTTJ8gqdtpWuECQQDW2MMV9c/oH6GsDk9l9UCOmoNHFmQkPLV90/ws35Oj" + "\r" +
                    "tsqpYv4KP4ZbUaw7pkJkCPHzHfYAI0xw1C67GQUrGKtZAkEAzZ+a66FkxJcext0Q" + "\r" +
                    "Dz+lu1JMkE79zXVET310h6JY/xAKuqOCAw+pQcQQv8XuEi3OxnMZcfD1KFh0Zuxu" + "\r" +
                    "mutLYwJBANFtgt2JPB09mE8rs+HjbAaWP5mwDfX058W8OnlTh4tyx6LOSGyc989U" + "\r" +
                    "kdujedwhjBg9AGup/P2PF+5xuUQFTCECQBwb6HKzsnHJctSenbZn7gEIhBzqH3n5" + "\r" +
                    "wOfY75gnEmFz0POorHo8ptettNhyd1QW3QB19ZGE7g6g4PC8+3XEGp8CQDHOTLDo" + "\r" +
                    "UxB7dO3W5q2DFFjbbWNB/Fw2DRMbh6xYLrLNXoXRUByjCbKtDLuRF2PnUlMIEaV/" + "\r" +
                    "EB011IK3iTQMLYc=";
    public static String marhuiUrl = "http://localhost:8080/proOneMobile/forward/fcn.action";
    private static Logger log = Logger.getLogger(HttpClientUtils.class);

    static {//安全性
        Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
    }

    public static String jami(String json, String des3Key, String publicKey) throws Exception {
        String terminalTypeId = new String(Base64.encode("1".getBytes("UTF-8")), "UTF-8");
        RSAObjectC rsaEncrypt = RSAObjectC.getInstance(publicKey, DEFAULT_PRIVATE_KEY);
        byte[] desKeyB = rsaEncrypt.encryptNew(rsaEncrypt.getPublicKey(), des3Key.getBytes("Utf-8"));
        String desKey = new String(Base64.encode(desKeyB), "UTF-8");
        log.debug("#" + desKey + "#");
        log.debug("#################json#" + json + "#");
        String data = Des3.encode(json, des3Key);

        log.debug("#" + data + "#");
        String str = terminalTypeId + "|" + desKey + "|" + data;
        log.debug("参数：" + str);
        return str;
    }

    public static String httpClientUtils(String json, String urlStr, String publicKey) throws Exception {
        log.warn("请求URL:" + urlStr);
        log.warn("请求参数:" + json);
        String des3Key = Des3.generate32Key();
        log.warn("des3Key:" + des3Key);
        String xmlString = jami(json, des3Key, publicKey);
        String Method = "POST";

        byte[] xmlData = null;
        try {
            xmlData = xmlString.getBytes("UTF-8");
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        BufferedReader rd = null;
        String msg = "";

        try {
            URL url = new URL(urlStr);
            HttpURLConnection urlCon = (HttpURLConnection) url.openConnection();
            urlCon.setDoOutput(true);
            urlCon.setDoInput(true);
            urlCon.setUseCaches(false);
            urlCon.setRequestMethod(Method);
            urlCon.setConnectTimeout(120000);
            urlCon.setReadTimeout(120000);
            urlCon.setRequestProperty("Content-Type", "text/xml;charset=utf-8");
            urlCon.setRequestProperty("Content-length", String.valueOf(xmlData.length));
            urlCon.setRequestMethod("POST");
            DataOutputStream printout = new DataOutputStream(urlCon.getOutputStream());
            printout.write(xmlData);
            printout.flush();
            printout.close();
            log.warn("数据发送完成,等待响应...");
            rd = new BufferedReader(new InputStreamReader(urlCon.getInputStream(), "utf-8"));
            String inputLine;
            while ((inputLine = rd.readLine()) != null)
                msg += inputLine;
            log.warn("解密前数据:" + msg);
            //解密
            String[] strArray = msg.split("\\|");
            if (strArray.length == 3) {
                if ("1".equals(strArray[0])) {//成功信息
                    log.warn("密文:" + strArray[1] + "#");
                    log.warn("deskey:" + des3Key + "#");
                    String data = Des3.decode(strArray[1], des3Key);
                    msg = data;
                    log.warn("响应数据为:" + msg);
                } else {
                    String code = strArray[1];
                    log.warn("错误代码:" + code);
                    String eMsg = new String(Base64.decode(strArray[2].getBytes("UTF-8")), "UTF-8");
                    log.warn("错误描述:" + eMsg);
                    msg = "{\"reqCode\":" + code + ",\"reqMsg\":" + eMsg + "}";
                }
            }
            rd.close();
        } catch (Exception e) {
            //e.printStackTrace();
            throw e;
        }
        return msg;
    }
}